# Filters added to this controller apply to all controllers in the application.
# Likewise, all the methods added will be available for all controllers.

class ApplicationController < ActionController::Base
  # Pick a unique cookie name to distinguish our session data from others'
  session :session_key => '_scrumbag_session_id'
  before_filter :check_authentication, :except => [:signin, :signout]

  def check_authentication
    unless session[:user]
      session[:intended_action] = action_name
      session[:intended_controller] = controller_name
      redirect_to :controller => "users", :action => "signin"
    end
  end
  
  def signin
    if request.post?
      u = User.find(:all)
      if u.length == 0
        newUser = User.new(:username => 'admin')
        newUser.password = 'admin'
        newUser.save
      end
      user = User.find(:first, :conditions => ['username = ?', params[:username]])
      if user.blank? || 
        Digest::SHA256.hexdigest(params[:password] + user.password_salt) != user.password_hash
        raise "Username or password invalid"
      end
      session[:user] = user.id
      redirect_to :action => session[:intended_action], :controller => session[:intended_controller]
    end
  end
  
  # Sign out
  def signout
    session[:user] = nil
  end
end
